package com.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description:Shiro JWT权限过滤器
 * @date: 2018/11/23 11:28
 */

public class JwtFilter extends AbstractSecurityFilter
{

    /**
     * 是否拦截
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response)
    {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        return token != null;
    }

    /**
     * 执行登录
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response)
    {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");

        JwtToken jwtToken = new JwtToken(token);
        //提交给realm进行登入
        getSubject(request, response).login(jwtToken);
        return true;
    }

    /**
     * 是否允许访问
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
    {
        if (isLoginAttempt(request, response))
        {
            try
            {
                executeLogin(request, response);
            }
            catch (Exception e)
            {

            }
        }
        return true;
    }
}
